package cn.com.byte1024.controller;

import cn.com.byte1024.entity.RegisterLog;
import cn.com.byte1024.entity.User;
import cn.com.byte1024.service.RegisterLogService;
import cn.com.byte1024.service.UserService;
import cn.com.byte1024.utils.CodeUtils;
import cn.com.byte1024.utils.CommonUtil;
import cn.com.byte1024.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName: VoteSystem
 * @ClassName: RegisterLogController
 * @Description:
 * @Author: Kwnda
 * @Date: 2021/1/4 15:25
 */
@Controller
@RequestMapping("/register")
public class RegisterLogController {

    @Autowired
    private UserService userService;

    @Autowired
    private RegisterLogService registerLogService;
    
    @RequestMapping("/goRegisterJsp")
    public String toRegisterJsp(){
        return "register";
    }

    @ResponseBody
    @RequestMapping("/sendSMS")
    public String sendSMS(String phone){
        //将前端发来的号码添加(+86)前缀 例如：+8612345678910
        String[] phoneNumbers  = new String[]{"+86"+phone};
        //通过手机账号查询是否有该用户，有则不发送验证码并且提示
        User user =userService.selectByLoginName(phone);
        if(user!=null){
            //该手机用户存在
            return "The mobile phone user ("+phone+") exists";
        }
        //生成验证码前检测该手机10分钟内是否发送过验证码，有则不发送（之前验证码还可以用），无或者过10分钟了则生成验证码并且发送
        List<RegisterLog> registerLogList = registerLogService.selectRegisterLogByPhone(phone);
        //该手机号码发送过注册码并且未使用，
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(registerLogList.size()>0){
            //判断该注册码是否过期（10分钟）
            for (RegisterLog registerLog : registerLogList) {
                //取当前时间作为end_time;与生成验证码时间相减小于600000，说明验证码还可以使用
                String end_time = sdf.format(new Date());
                Date date1=null,date2=null;
                try {
                    date1=sdf.parse(end_time);
                    date2=sdf.parse(registerLog.getBeginTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                long date = date1.getTime() - date2.getTime();
                if(date<600000)
                    return "The SMS verification code you previously applied for can still be used";
            }
        }
        //调用随机生成6位验证码
        String valcode= CodeUtils.GenerateVerificationCode();
//		String valcode="123456";
        //调用发送短信验证码工具
        SmsUtils.sendSms(valcode, phoneNumbers);
        //调用service保存手机号码、验证码、发送时间,设置验证码可用
        RegisterLog log = new RegisterLog();
        log.setRegisterId(CommonUtil.generateUUID());
        log.setPhone(phone);
        log.setCode(valcode);
        log.setBeginTime(sdf.format(new Date()));
        log.setIsValid("1");
        registerLogService.saveRegisterCode(log);
        return "SMS sent successfully";
    }

    @ResponseBody
    @RequestMapping("/saveRegister")
    public String saveRegister(@RequestParam("phone") String phone, @RequestParam("smsCode") String smsCode, @RequestParam("userName") String userName, @RequestParam("password") String password){
        User user =userService.selectByLoginName(phone);
        if(user!=null){
            //该手机用户存在
            return "The mobile phone user ("+phone+") exists";
        }
        //取当前时间和数据库code获取的时间进行比较，如果code超过10分钟（end_time-begin_time）
        List<RegisterLog> registerLogList = registerLogService.selectRegisterLogByCode(phone,smsCode);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf.format(new Date());
        int num=0;
        for (RegisterLog registerLog : registerLogList) {
            Date date1=null,date2=null;
            try {
                date1=sdf.parse(endTime);
                date2=sdf.parse(registerLog.getBeginTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long date = date1.getTime() - date2.getTime();
            if(date>600000)
                num++;

        }
        if(registerLogList.size()<num){
            return "The verification code has expired, please apply again";
        }
        //否则保存注册记录
        RegisterLog log = new RegisterLog();
        log.setPhone(phone);
        log.setEmail("");
        log.setIsRegist("1");
        log.setIsValid("0");
        log.setEndTime(endTime);
        registerLogService.updateRegister(log);
        
        //保存用户（login_name,user_name,password）
        User userNew = new User();
        userNew.setUserId(CommonUtil.generateUUID());
        userNew.setLoginName(phone);
        userNew.setUserName(userName);
        userNew.setPassword(password);
        userNew.setPhone(phone);
        userNew.setEmail("");
        userService.saveUser(userNew);
        return "registration success";
    }
}
